//登录的用户相关信息
import { isNoNullOrUndefind } from "@/utils/utils"
import { ifrememberLogin } from "@/api/customer"
import { jsonToObj } from "@/utils/utils"
const state={
  //用户基本信息
    // customer:{
    //   id:'frgtbgrhdefrgtryn',
    //   name:Mock.mock('@cname'),
    //   nickname:'efrvbgnh',
    //   password:'efrgtbgn',
    //   
    // },
    // 用户登录信息
    // account:{
    //   ip:'',
    //   logintime:'',
    //   token:'',
    // },
    customer:null,
    account:null,
}
const actions={
    login(context,obj){
      // console.log(obj.customer)
      if(isNoNullOrUndefind(obj)) context.commit('login',obj)
    },
    //刷新或初始化页面时 把sessionStorage或localStorage的用户信息挂到vuex中
    refreshpage(context){
      let customer = jsonToObj( window.sessionStorage.getItem('customer'))
      // console.log(customer)
      let account = jsonToObj( window.sessionStorage.getItem('account'))
      if(isNoNullOrUndefind(customer)&&isNoNullOrUndefind(account)){
        
        context.commit('login',{customer,account})
       return
      }
      customer = jsonToObj( window.localStorage.getItem('customer'))
      // console.log('测试'+JSON.stringify(customer))
      account = jsonToObj( window.localStorage.getItem('account'))
      // console.log(JSON.stringify(customer))
      if(isNoNullOrUndefind(customer)&&isNoNullOrUndefind(account)){
        //想后台发送请求 查询用户是否存在
        ifrememberLogin(customer,account).then(res=>{
            if(isNoNullOrUndefind(res.customer)&&isNoNullOrUndefind(res.account)){
             context.commit('login',{customer:res.customer,account:res.account})
             console.log(context.state.account.logintime);
            // console.log(JSON.stringify(context.state.customer))
         
             context.commit('localStorage')
            }
        })
        
       return
      }
    }
}
const mutations={
  login(state,obj){
    
    state.customer=obj.customer
    state.account=obj.account
    // console.log('设置'+JSON.stringify(state.customer))
    // 存储在sessionStorage中
    window.sessionStorage.setItem('customer',JSON.stringify( state.customer))
    window.sessionStorage.setItem('account',JSON.stringify(state.account))
  },
  //存储用户到本地
  localStorage(state){
    if(!isNoNullOrUndefind(state.customer)||!isNoNullOrUndefind(state.account)){
      alert('用户不存在,无法存储')
      
    }else{
      window.localStorage.setItem('customer',JSON.stringify(state.customer))
      window.localStorage.setItem('account',JSON.stringify(state.account))
    }
  }
}
const getters={
  //用户是否是登录
    isLogin(state){
       const customer= state.customer;
      const account= state.account
      return isNoNullOrUndefind(customer)&&isNoNullOrUndefind(account)
    },
      
}


export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations,
 
  }